﻿using gt.webapi.core.Entity.Common;
using gt.webapi.core.Extensions;
using gt.webapi.core.Logging;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Results;

namespace gt.webapi.core.Handlers
{

    ///IExceptionLogger作为异常日志记录组件，负责异常发生后的日志记录，他贯穿于整个Web API的生命周期中，在Web API框架里，任何一个请求周期中出现任何一个未被捕获/处理的异常都会首先进入这个异常日志记录管道进行异常Log记录，在Web API中可以注册多个IExceptionLogger实例负责不同的异常处理。
    ///IExceptionHandler作为异常处理组件，负责异常发生后的处理工作，他处于异常处理管道的最末端，当IExceptionLogger组件进行一场记录完毕、没有相关的ExceptoinFilter进行异常处理时，才会最终调用ExceptionHandler进行异常处理，在Web API中，有且仅有一个ExceptionHandler进行异常的处理。
    /// <summary>
    /// 通用Error拦截，包括Handler内部错误
    /// the solution for customizing all possible responses to unhandled exceptions caught by Web API
    /// </summary>
    public class ErrorHandler : IExceptionHandler
    {
        private ApiLogger m_logger = null;
        public ErrorHandler(ApiLogger logger)
        {
            this.m_logger = logger;
        }
        public async Task HandleAsync(ExceptionHandlerContext context, System.Threading.CancellationToken cancellationToken)
        {
            Exception ex = context.Exception;
            if (ex != null)
            {
                //返回值设置
                HttpResponseMessage response = context.Request.CreateResponse<ApiResponse<string>>(
                    HttpStatusCode.OK,
                    new ApiResponse<string>(999, Constants.ERROR_SYSTEM),
                    Constants.API_CONTENT_MEDIATPE_JSON);

                context.Result = new ResponseMessageResult(response);

                var requestId = context.Request.GetRequestId();
                this.m_logger.Error(requestId, ex);
            }
            await Task.FromResult(0);
        }
    }

    //public class ErrorHandler : ExceptionHandler
    //{
    //    public override void Handle(ExceptionHandlerContext context)
    //    {
    //        Exception ex = context.Exception;
    //        if (ex != null)
    //        {
    //            //返回值设置
    //            HttpResponseMessage response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, Constants.UN_KNOW_ERROR);
    //            context.Result = new ResponseMessageResult(response);
    //            string apiKey = context.Request.Properties[Constants.API_REQUEST_KEY] == null ? string.Empty
    //                : context.Request.Properties[Constants.API_REQUEST_KEY].ToString();
    //            ApiLogHelper.Error(apiKey, ex);
    //        }
    //    }

    //    //public override bool ShouldHandle(ExceptionHandlerContext context)
    //    //{
    //    //    return context.CatchBlock.IsTopLevel;
    //    //}
    //}

    //the solution to seeing all unhandled exception caught by Web API.
    //public class GlobalExceptionLog : ExceptionLogger
    //{
    //    public override Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)
    //    {
    //        return base.LogAsync(context, cancellationToken);
    //    }
    //}
}
